package android.grapro.testing;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {
	String path = Environment.getExternalStorageDirectory().getAbsolutePath();
	private List<String>directoryEntries = new ArrayList<String>();
	private List<String> item = new ArrayList<String>(); //Name of File and Folder
	private File currentDirectory = new File(path);
	
	private MediaPlayer mPlayer = new MediaPlayer();
	
	private int VISIBLE = 1;
	private int INVISIBLE = -1;
	
	private ListView lv;
	private TextView titleManager;
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_LEFT_ICON);
        setContentView(R.layout.main);
        setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.file_browser_icon);
        
        lv = (ListView)findViewById(R.id.list);
        
        browseTo(new File(path));
        
        ImageButton upLevelButton = (ImageButton)findViewById(R.id.upParentFolder);
        upLevelButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				stopPlayMusicFile();
				upOnLevel();
			}
		});
        
        onItemClick(lv);
    }
    
    //browse to parent directory
    private void upOnLevel(){
    	if(this.currentDirectory.getParent() != null){
    		this.browseTo(this.currentDirectory.getParentFile());
    	}
    }
    
    //browser to file or directory
    private void browseTo(final File aDirectory){
    	//if we want to browse directory
    	if(aDirectory.isDirectory()){
    		//fill list with files from this directory
    		this.currentDirectory = aDirectory;
    		fill(aDirectory.listFiles());
    		
    		//set titleManager text
    		titleManager = (TextView)findViewById(R.id.pathName);
    		titleManager.setText(aDirectory.getAbsolutePath());
    	}else {
    		
    		Toast.makeText(MainActivity.this, "Open file", Toast.LENGTH_LONG).show();
    	}
    }
    
    //fill list
    private void fill(final File[]files){
    	//clear list
    	directoryEntries.clear();
    	item.clear();
    	
    	for(File file:files){
    		directoryEntries.add(file.getAbsolutePath());
    		item.add(file.getName());
    	}
    	
    	//create array adapter to show everything
    	ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this, R.layout.list_folder_file, item){
    		@Override
			public View getView(int position, View v, ViewGroup parent) {
    			
				if(v == null){
					LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					v = vi.inflate(R.layout.list_folder_file, null);
				}
				
				//Check null exception
				Log.i("item Length: ",String.valueOf(item.size()));
				Log.i("dicrectoryEntries Length: ", String.valueOf(directoryEntries.size()));
				Log.i("files Length: ", String.valueOf(files.length));
				
				if(files != null){
					try{
						
						ImageView icon = (ImageView)v.findViewById(R.id.icon);
						CheckBox chk = (CheckBox)v.findViewById(R.id.checkbox);
						ImageView arrow = (ImageView)v.findViewById(R.id.arrow);
						TextView filefolderName = (TextView)v.findViewById(R.id.folderName);
						
						filefolderName.setText(item.get(position).toString());
						if(files[position].isDirectory()){
							Log.i("Ngon chua?", "OK");
							arrow.setVisibility(VISIBLE);
							chk.setVisibility(INVISIBLE);
							
							filefolderName.setTypeface(null, Typeface.BOLD);
							icon.setBackgroundResource(R.drawable.folder_icon);
							
						}
						if(files[position].isFile()){
							chk.setVisibility(VISIBLE);
							arrow.setVisibility(INVISIBLE);
							if(CheckFile.isAPKFile(files[position]))
								icon.setBackgroundResource(R.drawable.apk);
							else if(CheckFile.isBMPFile(files[position]))
								icon.setBackgroundResource(R.drawable.bmp_icon);
							else if(CheckFile.isJPEGFile(files[position]))
								icon.setBackgroundResource(R.drawable.jpeg_icon);
							else if(CheckFile.isJPGFile(files[position]))
								icon.setBackgroundResource(R.drawable.jpg_icon);
							else if(CheckFile.isPNGFile(files[position]))
								icon.setBackgroundResource(R.drawable.png_icon);
							else if(CheckFile.isGIFFile(files[position]))
								icon.setBackgroundResource(R.drawable.gif_icon);
							else if(CheckFile.isWordFile(files[position]))
								icon.setBackgroundResource(R.drawable.word_icon);
							else if(CheckFile.isPowerpointFile(files[position]))
								icon.setBackgroundResource(R.drawable.ppt_icon);
							else if(CheckFile.isExelFile(files[position]))
								icon.setBackgroundResource(R.drawable.excel_iconl);
							else if(CheckFile.isPDFFile(files[position]))
								icon.setBackgroundResource(R.drawable.pdf_icon);
							else if(CheckFile.isMP3File(files[position]))
								icon.setBackgroundResource(R.drawable.mp3_icon);
							else if(CheckFile.isWMAFile(files[position]))
								icon.setBackgroundResource(R.drawable.wma_icon);
							else if(CheckFile.isHTMLFile(files[position]))
								icon.setBackgroundResource(R.drawable.html_icon);
							else if(CheckFile.isXMLFile(files[position]))
								icon.setBackgroundResource(R.drawable.xml_icon);
							else if(CheckFile.isTXTFile(files[position]))
								icon.setBackgroundResource(R.drawable.txt_icon);
							else
								icon.setBackgroundResource(R.drawable.file_icon);
							
						}
						
					}catch(Exception e){
						e.printStackTrace();
					}
				}
				return v;
			}
    	};
    	lv.setAdapter(directoryList);
    }
    
    public void onItemClick(ListView lv){
    	lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				stopPlayMusicFile();
				int selectionRowID = arg2;
				String selectedFileString = directoryEntries.get(selectionRowID);
				File clickedFile = null;
		        clickedFile = new File(selectedFileString);
		        if(clickedFile.listFiles() != null)
		        		browseTo(clickedFile);
		        else{
		        	if(clickedFile.isDirectory()){
		        		Toast.makeText(MainActivity.this, "don't permit access\nOr Directory empty!", Toast.LENGTH_LONG).show();
		        		titleManager.setText(directoryEntries.get(selectionRowID));
		        	}
		        	else{
		        		titleManager.setText(directoryEntries.get(selectionRowID));
		        		if(CheckFile.isTXTFile(clickedFile)){
		        			Intent intent = new Intent(MainActivity.this, ReadTextFile.class);
		        			intent.putExtra("pathFile", directoryEntries.get(selectionRowID));
		        			startActivityForResult(intent, 2);
		        		}
		        		else if(CheckFile.isMP3File(clickedFile)||CheckFile.isWMAFile(clickedFile))
		        			playMusicFile(clickedFile);
		        		else
		        			launchFile(clickedFile);
		        	}
		        		
		        }
		        	
			}
    		
		});
    }
    
    public void launchFile(File file){
    	Uri uri = Uri.fromFile(file);
    	String extension = getExtension(file.getName());
    	Intent intent = new Intent(Intent.ACTION_VIEW);
    	intent.setDataAndType(uri, MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension));
    	intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    	try{
    		startActivity(intent);
    	}catch(ActivityNotFoundException e){
    		Toast.makeText(MainActivity.this, "No Application available to view this file", Toast.LENGTH_LONG).show();
    	}
    }
    
    //Start Play music file when click music file
    public void playMusicFile(File mediaFile){
    	Uri uri = Uri.fromFile(mediaFile);
    	mPlayer = MediaPlayer.create(MainActivity.this, uri);
    	mPlayer.start();
    }
    public void stopPlayMusicFile(){
    	if(mPlayer.isPlaying())
    		mPlayer.stop();
    	
    }
    @Override
    public void onStop(){
    	super.onStop();
    	mPlayer.stop();
    }
    
    public String getExtension(String fileName){
    	return (fileName.substring(fileName.length() -3));
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event){
    	if((keyCode == KeyEvent.KEYCODE_BACK)){
    		if(this.currentDirectory.getParentFile() != null){
    			browseTo(currentDirectory.getParentFile());
    			stopPlayMusicFile();
    		}else{
//        		Toast.makeText(MainActivity.this, "No directory", Toast.LENGTH_SHORT).show();
        		finish();
    		}
    	}
    	return true;
    }
}